<template>
	<view class="layout">
		<wd-navbar title="入库扫码"  left-text="返回" @click-left="uni.navigateBack" left-arrow/>
		<wd-toast />
		<wd-cell-group border>
			<wd-cell 
				title="选择仓库" 
				:value="selectedWarehouseName || '请选择仓库'"
				is-link
				@click="showWarehouseSelector"
			/>
		<wd-input 
			label="成品信息" 
			v-model="scanContent"
			placeholder="点击右侧图标或按PDA扫描键扫码" 
			@clicksuffixicon="onScan"
			@click="onInputClick"
			suffix-icon="qrcode"
			readonly
		/>
		</wd-cell-group>
		
		<!-- 扫码解析内容显示 -->
		<wd-cell-group border v-if="parsedData.processCardId">
			<wd-cell title="流程卡批号" :value="parsedData.batchNumber" />
			<wd-cell title="小卷规格" :value="parsedData.smallRollSpec" />
		</wd-cell-group>
		
		<!-- 数量输入框 -->
		<wd-cell-group border v-if="parsedData.processCardId">
			<wd-input 
				label="数量" 
				v-model="quantity"
				placeholder="请输入数量" 
				type="number"
				class="quantity-input"
			/>
		</wd-cell-group>
		
		
		
		<view class="footer">
			<wd-button type="primary" size="large" @click="onSubmit" block>提交</wd-button>
		</view>
	</view>
</template>

<script setup>
	import { onMounted, onUnmounted, ref, computed, reactive } from 'vue';
	import { ProcessService } from '@/services';
	import { useToast } from '@/uni_modules/wot-design-uni';
	
	const toast = useToast();
	
	// 选中的仓库ID
	const selectedWarehouseId = ref('');
	
	// 仓库列表
	const warehouseList = ref([]);
	
	// 扫描内容
	const scanContent = ref('');
	
	// 数量
	const quantity = ref('');
	
	// 解析后的数据
	const parsedData = reactive({
		processCardId: '',
		batchNumber: '',
		smallRollId: '',
		smallRollSpec: ''
	});
	
	// 选中的仓库名称
	const selectedWarehouseName = computed(() => {
		if (!warehouseList.value || warehouseList.value.length === 0) {
			return '';
		}
		const warehouse = warehouseList.value.find(item => item.id === selectedWarehouseId.value);
		return warehouse ? warehouse.warehouseName : '';
	});
	
	// 显示仓库选择器
	const showWarehouseSelector = () => {
		if (warehouseList.value.length === 0) {
			toast.error('暂无可选择的仓库');
			return;
		}
		
		if (typeof uni !== 'undefined') {
			uni.showActionSheet({
				itemList: warehouseList.value.map(item => item.warehouseName),
				success: (res) => {
					selectedWarehouseId.value = warehouseList.value[res.tapIndex].id;
				},
				fail: function (err) {
					console.error('显示选择器失败:', err);
				}
			});
		} else {
			toast.error('选择功能不可用');
		}
	};
	
	// 输入框点击处理
	const onInputClick = () => {
		console.log('输入框被点击，触发扫码');
		onScan();
	};
	
	// 扫码功能
	const onScan = () => {
		console.log('点击扫码图标，打开相机扫码');
		uni.scanCode({
			onlyFromCamera: true,
			scanType: ['qrCode', 'barCode'],
			success: function (res) {
				console.log('相机扫码成功:', res.result);
				handleQRCode(res.result);
			},
			fail: function (err) {
				console.error('相机扫码失败:', err);
				toast.error('扫码失败');
			}
		});
	};
	
	// 解析二维码内容
	const parseQRCode = (qrContent) => {
		try {
			console.log('=== 开始解析产品二维码 ===');
			console.log('二维码内容:', qrContent);
			
			// 按照_zjhy_分割内容
			// 格式: 流程卡id_zjhy_流程卡批号_zjhy_小卷id_zjhy_小卷型号(小卷规格)
			const parts = qrContent.split('_zjhy_');
			console.log('分割后的部分:', parts);
			
			if (parts.length >= 4) {
				parsedData.processCardId = parts[0]; // 流程卡ID
				parsedData.batchNumber = parts[1];   // 流程卡批号  
				parsedData.smallRollId = parts[2];   // 小卷ID
				parsedData.smallRollSpec = parts[3] || ''; // 小卷规格
				
				console.log('解析成功，产品信息:', {
					processCardId: parsedData.processCardId,
					batchNumber: parsedData.batchNumber,
					smallRollId: parsedData.smallRollId,
					smallRollSpec: parsedData.smallRollSpec
				});
				
				toast.success('扫码解析成功，请选择仓库并输入数量后提交');
				console.log('=== 等待用户选择仓库和输入数量 ===');
			} else {
				console.error('二维码格式错误，部分数量:', parts.length);
				toast.error(`二维码格式不正确，应包含4个部分，实际包含${parts.length}个部分`);
			}
		} catch (error) {
			console.error('解析二维码失败:', error);
			toast.error('解析二维码失败');
		}
	};
	
	// 加载仓库列表
	const loadWarehouseList = async () => {
		try {
			const response = await ProcessService.getWarehouseList();
			if (response.code === 200 && response.rows) {
				warehouseList.value = response.rows.filter(item => item.dataStatus === 1);
			} else {
				toast.error('加载仓库列表失败');
			}
		} catch (error) {
			toast.error('加载仓库列表失败');
		}
	};

	// 保存成品登记
	const saveFinishedProduct = async () => {
		try {
			console.log('=== saveFinishedProduct 函数被调用 ===');
			const params = {
				processCardId: parsedData.processCardId,  // 流程卡ID
				smallRollSpecId: parsedData.smallRollId,  // 小卷规格ID  
				warehouseId: selectedWarehouseId.value,   // 仓库ID
				quantity: quantity.value,                 // 数量
				direction: "入库"                         // 固定值：入库
			};
			
			console.log('开始保存成品登记，参数:', params);
			
			uni.showLoading({
				title: '保存中...',
				mask: true
			});
			
			const response = await ProcessService.saveFinishedProduct(params);
			
			console.log('接口返回结果:', response);
			
			uni.hideLoading();
			
			if (response && response.code === 200) {
				console.log('保存成功');
				
				// 保存成功后询问是否查看入库信息
				uni.showModal({
					title: '保存成功',
					content: '成品登记保存成功，是否查看入库信息？',
					confirmText: '查看',
					cancelText: '继续扫码',
					success: (res) => {
						if (res.confirm) {
							// 跳转到入库信息页面，并传递参数
							const query = `processCardId=${params.processCardId}&smallRollSpecId=${params.smallRollSpecId}`;
							uni.redirectTo({
								url: `/pages/store_info/store_info?${query}`
							});
						} else {
							// 清空表单继续扫码
							quantity.value = '';
							selectedWarehouseId.value = '';
							Object.assign(parsedData, {
								processCardId: '',
								batchNumber: '',
								smallRollId: '',
								smallRollSpec: ''
							});
						}
					}
				});
			} else {
				console.error('保存失败，返回码:', response?.code, '消息:', response?.msg);
				uni.showToast({
					title: response?.msg || '保存失败',
					icon: 'error',
					duration: 2000
				});
			}
		} catch (error) {
			console.error('保存成品登记异常:', error);
			uni.hideLoading();
			uni.showToast({
				title: '网络错误，保存失败',
				icon: 'error',
				duration: 2000
			});
		}
	};

	// 处理扫码结果的统一函数
	const handleQRCode = (code) => {
		console.log('=== 出入库扫码页面PDA扫码触发 ===');
		console.log('当前页面确认: store_scan.vue (出入库扫码页面)');
		console.log('PDA扫码接收到数据:', code);
		
		// 显示明确的提示，确认在正确页面
		toast.info('在出入库扫码页面接收到扫码数据');
		
		if (!code) {
			toast.error('扫码数据为空');
			return;
		}
		
		// 不在输入框中显示扫描内容，直接解析
		parseQRCode(code);
	};

	onMounted(() => {
		console.log('=== 出入库扫码页面加载 ===');
		console.log('开始监听 PDA 扫码事件');
		console.log('当前页面路径:', getCurrentPages()[getCurrentPages().length - 1].route);
		loadWarehouseList();
		
		// 先移除所有可能存在的旧监听器
		console.log('清除所有旧的 urovo 监听器');
		uni.$off("urovo");
		
		// 监听设备扫码（PDA 物理按键扫码）
		uni.$on("urovo", handleQRCode);
		console.log('出入库扫码页面 PDA 扫码监听器已注册');
	});
	
	onUnmounted(() => {
		// 移除设备扫码监听
		uni.$off("urovo", handleQRCode);
	});

	const onSubmit = () => {
		console.log('=== onSubmit 函数被调用 ===');
		console.log('调用堆栈:', new Error().stack);
		console.log('当前状态检查:');
		console.log('- selectedWarehouseId:', selectedWarehouseId.value);
		console.log('- processCardId:', parsedData.processCardId);
		console.log('- quantity:', quantity.value);
		
		if (!selectedWarehouseId.value) {
			console.log('❌ 缺少仓库选择');
			toast.error('请选择仓库');
			return;
		}
		
		if (!parsedData.processCardId) {
			console.log('❌ 缺少产品二维码');
			toast.error('请先扫描产品二维码');
			return;
		}
		
		if (!quantity.value) {
			console.log('❌ 缺少数量输入');
			toast.error('请输入数量');
			return;
		}
		
		console.log('✅ 所有条件满足，开始提交');
		saveFinishedProduct();
	}
</script>

<style scoped>
	.layout {
		padding: 16rpx;
	}
	
	
	/* 数量输入框右对齐 */
	.quantity-input :deep(.wd-input__value) {
		text-align: right;
	}
</style>